<template>
  <div>
    <el-dialog title="处理工单" :visible.sync="dialogVisible" :width="editInfo.status == 3 ? '620px' : '450px'"
      :show-close="false" :close-on-click-modal="false" :append-to-body="true">
      <el-form :model="addInfo" :rules="rules" ref="refAddInfo" label-width="78px"
        :style="'height: ' + editInfo.status == 3 ? '20vh' : '14vh'">
        <el-form-item size="small" :label="getlabel" prop="status" v-if="editInfo.status != 1">
          <el-radio-group v-model="addInfo.status">
            <el-radio :label="item.id" v-for="(item, index) in statusList" :key="index">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- <el-form-item size="small" label="维保技工" prop="maintenanceUserId"
          v-if="editInfo.status == 1 || addInfo.status == 11">
          <el-select v-model="addInfo.maintenanceUserId" filterable placeholder="请选择维保技工" class="elSelect"
            style="width: 100%">
            <el-option v-for="(item, i) in maintenanceList" :key="i" :label="item.username + '：' + item.mobile"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item> -->
         <el-form-item size="small" label="抄送人" v-if="addInfo.status == 5">
                      <el-select v-model="addInfo.userIds" filterable multiple collapse-tags placeholder="请选择抄送人"
                        style="width: 100%" size="small" clearable>
                        <el-option v-for="(item, i) in fcrDutyUserRelatedVO" :key="i" :label="item.userName" :value="item.userId">
                        </el-option>
                      </el-select>
                    </el-form-item>

        <el-form-item size="small" label="处理人" v-if="addInfo.status == 11" prop="maintenanceUserId">
          <el-select v-model="addInfo.maintenanceUserId" filterable placeholder="请选择处理人" style="width: 100%"
            size="small" clearable>
            <el-option v-for="(item, i) in fcrDutyUserRelatedVO" :key="i" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

       

        <el-form-item size="small" label="图片" v-if="addInfo.status == 4 || addInfo.status == 5">
          <div style="width: 100%">
            <el-upload :class="{ disabled: uploadDisabled }" :on-remove="handleRemove" :on-change="uploadSectionFile"
              :action="baseUrl" :file-list="fileList" list-type="picture-card" accept=".jpg,.png"
              :on-preview="handlePictureCardPreview" :headers="headers" :before-upload="beforeAvatarUpload"
              :on-success="handleSuccessFunction" :limit="5" :on-exceed="handleExceedScene" :on-error="uploadFileError">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item size="small" label="视频" v-if="addInfo.status == 4 || addInfo.status == 5">
          <el-upload class="upload-demo" :action="baseUrl" :file-list="fileList" :headers="headers"
            :on-success="onsuccessVideo" accept=".mp4" :on-remove="handleVideo" multiple :limit="1"
            :on-exceed="handleExceed" :before-upload="beforeUploadVideo">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
         <el-form-item size="small" label="备注">
          <el-input type="textarea" :rows="2" placeholder="请输入备注内容" v-model="addInfo.remark" maxlength="100"
            resize="none" :autosize="{ minRows: 2, maxRows: 5 }" style="width: 100%"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" @click="addSubmit" v-preventReClick="1000" class="confirm-button">{{ editInfo.status ==
          1 ? "派 单" : "确 定" }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible2">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { reqMaintenance, reqWorkOrderUpdate, reqClosedLoop, reqGetDetails } from "@/api/api";
import { mapState } from "vuex";
import asc from "@utils/asc.js"; //加密解密

export default {
  props: ["editInfo"],
  mixins: [],
  data() {
    return {
      dialogVisible: false,
      addInfo: {
        maintenanceUserId: "",
        remark: "",
        status: 2,
        userIds:[]
      },
      // 表单验证规则
      rules: {
        maintenanceUserId: [
          {
            required: true,
            message: "请选择处理人",
            trigger: "change",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
      },
      maintenanceList: [],
      statusList: [
        {
          id: 2,
          name: "接单",
        },
        // {
        //   id: 3,
        //   name: "退单",
        // },
        {
          id: 11,
          name: "重新派单",
        },
      ],
      uploadDisabled: false, //加号默认显示
      headers: {
        token: asc.decrypt(sessionStorage.getItem("token")),
      },
      picList: [],
      fileList: [],
      dialogVisible2: false,
      dialogImageUrl: "",
      fcrDutyUserRelatedVO: [],
    };
  },
  computed: {
    ...mapState(["user"]),
    getlabel() {
      if (this.editInfo.status == 2) {
        return "是否接单";
      } else if (this.editInfo.status == 3) {
        return "维修状态";
      } else if (this.editInfo.status == 4 || this.editInfo.status == 5) {
        return "审核结果";
      }
    },
  },
  watch: {
    dialogVisible(e) {
      if (e) {
        this.getGetDetails()
        if (this.editInfo.status == 1 || this.editInfo.status == 2) {
          this.getDataList();
        }
        if (this.editInfo.status == 2) {
          this.baseUrl = `${this.$baseURL_copy}file/upload`;
          this.statusList = [
            {
              id: 2,
              name: "接单",
            },
            // {
            //   id: 3,
            //   name: "退单",
            // },
            {
              id: 11,
              name: "重新派单",
            },
          ];
          this.addInfo.status = 2;
        }
        if (this.editInfo.status == 3) {
          this.baseUrl = `${this.$baseURL_copy}file/upload`;
          this.statusList = [
            {
              id: 4,
              name: "修复中",
            },
            {
              id: 5,
              name: "修复完成",
            },
            {
              id: 11,
              name: "重新派单",
            },
          ];
          this.addInfo.status = 5;
        }
        if (this.editInfo.status == 4) {
          this.statusList = [
            {
              id: 6,
              name: "通过",
            },
            {
              id: 7,
              name: "不通过",
            },
          ];
          this.addInfo.status = 6;
        }
        if (this.editInfo.status == 5) {
          this.statusList = [
            {
              id: 8,
              name: "通过",
            },
            {
              id: 9,
              name: "不通过",
            },
          ];
          this.addInfo.status = 8;
        }
      }
    },
  },
  methods: {
    // 消控室列表
    async getGetDetails() {
      let res = await reqGetDetails(this.editInfo.imei);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res, 'res');
      this.fcrDutyUserRelatedVO = res.data.info.fcrDutyUserRelatedVO || [];//值班人员
    },
    // 维保技工
    async getDataList() {
      const res = await reqMaintenance(this.editInfo.maintenanceId);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      //    console.log(res);
      this.maintenanceList = res.data.rows;
    },
    addSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          if (this.addInfo.status != 11 && this.editInfo.status != 1) {
            this.addInfo.maintenanceUserId = "";
          }
          if (this.editInfo.status == 1) {
            this.addInfo.status = 1;
          }
          // let result='1'
          // if(this.addInfo.status==1){
          //   this.addInfo.status = 1;
          // }
          let params = {}
          if (this.addInfo.status == 11) {
            // 重新派单
            params = {
              id: this.editInfo.id,
              userId: this.user.userId,
              username: this.user.userName,
              status: this.addInfo.status,
              result: "1",
              remark: this.addInfo.remark,
              maintenanceUserId: this.addInfo.maintenanceUserId,
              picList: [],
              videoFile: '',
              userIds:[],
            }
          } else {
            params = {
              id: this.editInfo.id,
              userId: this.user.userId,
              username: this.user.userName,
              status: this.addInfo.status,
              result: "1",
              remark: this.addInfo.remark,
              maintenanceUserId: this.addInfo.maintenanceUserId,
              picList: this.picList,
              videoFile: this.videoFile || '',
              userIds:this.addInfo.userIds|| [],
            }
          }
          const res = await reqWorkOrderUpdate(params);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("处理成功！");
          // 完结
          if (this.addInfo.status == 5) {
            let res2 = await reqClosedLoop({
              id: this.editInfo.alarmId,
            });
            if (res2.code !== 20000) return this.$modal.notifyWarning(res2.message);
          }
          this.closeDialog();
          this.$parent.getDataList(); //更新列表
        }
      });
    },
    // 点击关闭弹框
    closeDialog() {
      this.dialogVisible = false;
      this.$refs.refAddInfo.resetFields();
      this.addInfo = {
        maintenanceUserId: "",
        remark: "",
        status: 2,
      };
      this.picList = [];
      this.fileList = [];
      this.videoFile = ''
    },
    //删除照片
    handleRemove(file, fileList) {
      // console.log(fileList);
      this.picList = [];
      fileList.forEach((item) => {
        if (item.response) {
          this.picList.push(item.response.data.url);
        } else {
          this.picList.push(item.url);
        }
      });
      setTimeout(() => {
        this.uploadDisabled = false;
      }, 1000);
    },
    // 文件状态改变时的钩子
    uploadSectionFile(file, fileList) {
      if (fileList.length >= 5) {
        this.uploadDisabled = true; //隐藏加号
      }
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      // console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      let isJPG = true;
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        this.$message.error("图片只能是 jpg/png 格式!");
        isJPG = false;
      }
      let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb  500
      if (!isLt) {
        this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
        this.uploadDisabled = false;
        isJPG = false;
      }
      return isJPG;
    },
    // 上传成功
    handleSuccessFunction(response, file, fileList) {
      this.picList.push(file.response.data.url);
    },
    // 文件超出个数限制时的钩子
    handleExceedScene() {
      this.$modal.notifyWarning(`照片最多6张`);
    },
    //上传失败
    uploadFileError(err, file, fileList) {
      this.uploadDisabled = false;
    },
    // 视频
    beforeUploadVideo(file) {
      const isLt30M = file.size / 1024 / 1024 < 30;
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
        ].indexOf(file.type) == -1
      ) {
        this.$modal.notifyWarning("请上传正确的视频格式");
        return false;
      }
      if (!isLt30M) {
        this.$modal.notifyWarning("上传视频大小不能超过30MB哦!");
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.$modal.notifyWarning(`只能上传一个视频文件`);
    },
    //删除视频
    handleVideo(file, fileList) {
      this.videoFile = "";
    },
    // 上传成功
    onsuccessVideo(response, file, fileList) {
      // console.log(file);
      this.videoFile = file.response.data.url;
    },
  },
  deactivated() {
    if (this.$refs.refAddInfo != null) {
      this.closeDialog();
    }
    this.dialogVisible2 = false;
  },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

//   单选按钮
::v-deep .el-radio {
  color: @primaryThemeTxtColor2;
}

::v-deep .el-radio__input.is-checked+.el-radio__label {
  color: #7367f0;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #7367f0;
  background: #7367f0;
}

// 照片隐藏加号
/deep/ .disabled .el-upload--picture-card {
  display: none !important;
}
</style>
